import React, {Component} from 'react'
import Dimensions from 'react-dimensions'
import {fetchData} from '../../components/AjaxConsumer'
import SelectUrl from '../../components/SelectUrl'
import {Form,
    Input,
    Tooltip,
    Icon,
    Row,
    Col,
    Checkbox,
    Button,
    message,
    Modal,
    Radio,
    Select
} from 'antd';
const Option = Select.Option;
const RadioGroup = Radio.Group;
const FormItem = Form.Item;

// 主要表单组件
class SelfForm extends React.Component {
    constructor(props) {
		super(props);
		this.state = {
            loading: false,
            confirmDirty: false,
            ruleId:'',
            ruleCode:'',
            ruleDesc:'',
            ruleLength:'',
            ruleDetalId:'',
            rowArr: [],
        };
    }
    componentDidMount () {
        console.log('--------',this.props.getData);
        this.setState({
            rowArr:this.props.getData.data,
            ruleCode:this.props.ruleCode
        })
    }
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, fieldsValue) => {
                if (!err) {
                    this.setState({loading: true});
                    //将fieldsValue深拷贝给value
                    let i = 0;
                    let result = {};
                    // for ( let e in fieldsValue){
                      //      result.beginLoc = fieldsValue.first1Rank.inputValue1
                      //      result.endLoc = fieldsValue.first1Rank.inputValue2
                      //      result.content = fieldsValue.first1Rank.inputValue3
                      //      result.includeContent = fieldsValue.first1Rank.inputValue4
                      //      result.excludeContent = fieldsValue.first1Rank.inputValue5
                      //      result.contentType = fieldsValue.first1Rank.selectValue

                    //     i = i + 1;
                    // }

                    for ( let e in fieldsValue){
                         this.state.beginLoc = fieldsValue[e].inputValue1
                         this.state.endLoc = fieldsValue[e].inputValue2
                         this.state.content = fieldsValue[e].inputValue3
                         this.state.includeContent = fieldsValue[e].inputValue4
                         this.state.excludeContent = fieldsValue[e].inputValue5
                         this.state.contentType = fieldsValue[e].selectValue
                    }

                    for ( let e in fieldsValue){
                         result.beginLoc = fieldsValue[e].inputValue1
                         result.endLoc = fieldsValue[e].inputValue2
                         result.content = fieldsValue[e].inputValue3
                         result.includeContent = fieldsValue[e].inputValue4
                         result.excludeContent = fieldsValue[e].inputValue5
                         result.contentType = fieldsValue[e].selectValue
                    }

                    var tmpfvList = new Array();

                    for ( let e in fieldsValue){
                        var tmpfv = {};

                         tmpfv.beginLoc = fieldsValue[e].inputValue1
                         tmpfv.endLoc = fieldsValue[e].inputValue2
                         tmpfv.content = fieldsValue[e].inputValue3
                         tmpfv.includeContent = fieldsValue[e].inputValue4
                         tmpfv.excludeContent = fieldsValue[e].inputValue5
                         tmpfv.contentType = fieldsValue[e].selectValue
                         tmpfv.ruleCode  = this.state.ruleCode
                         tmpfv.ruleDetalId = fieldsValue[e].ruleDetalId
                         tmpfvList.push(tmpfv);
                    }



                    let values = {
                        ...result,
                        ruleCode : this.state.ruleCode
                    };
                    //发送ajax 控制请求数据规则，无值的设为空
                    for (let item in values) {
                        if (!values[item]) {
                            values[item] = ''
                        }
                    }
                    //打印表单提交的值
                    console.log('from submit data:', values);

                    //在这里可以改造传给服务器的   values
                    let url = '';
                    let res = [...this.state]

                    console.log('resresresresres=====:', res);

                    //if(this.state.ruleCode == null || this.state.ruleCode == ''){
                    //    url = '/base/data/serialrule/cDetail';
                    //} else {
                    url = '/base/data/serialrule/uDetail';
                    //}

                    const options = {
                        //服务器的url
                        url: url,
                        type: 'post',
                        //condition:  values
                        //condition:  res[0]
                        condition:  JSON.stringify(tmpfvList),
                        contentType: 'application/json; charset=utf-8'
                        
                    };
                    fetchData(this, options, (res) => {
                        //回调函数
                        if (res.code == 1) {
                            message.success('操作成功');
                        }
                        setTimeout(() => {
                            // this.resetFrom();
                            this.props.onCancel();
                            this.setState({loading: false})
                            // console.log("刷新List列表")
                            this.props.refreshHandle();
                        }, 1000); //缓冲
                        
                    })
                }
            });
    }
    //增加一行优先级
    addRow = () => {
        let rowArr = this.state.rowArr;
        let newRow = {
                selectValue: '',
                inputValue1: '',
                inputValue2: '',
                inputValue3: '',
                inputValue4: '',
                inputValue5: '',
                ruleDetalId: '',
        }
        rowArr.push(newRow);
        if(rowArr.length > 5){
            alert("只能添加五条数据！");
            return;
        }
        this.setState({
            rowArr: rowArr
        })
    }
    //表单校验
    checkObj = (rule, value, callback) =>{
        //if (!value.selectValue) {
       //     callback('请选择内容类型');
       // }

        if(!value.inputValue1){
        callback('请输入内容类型！');
        }

        // if (!value.selectValue2) {
        //     callback('请选择库位');
        // }

        callback();
        return ;
    }

    render() {
        const {getFieldDecorator} = this.props.form;
        const headerStyle = {
            float: 'left',
            width: '120px',
            height: '50px',
            textAlign: 'center',
            lineHeight: '35px',
            fontSize: '14px',
            margin: '0 5px'
            // lineHeight: '50px'
        }
        const headerStyle2 = {
            float: 'left',
            width: '680px',
            height: '50px',
            textAlign: 'center',
            fontSize: '14px',
            margin: '0 5px'
            // lineHeight: '50px'
        }
        let rowArr = this.state.rowArr.map((e,index)=>{
            return (
                <div style={{width:'100%'}} key={index}>
                    {/*<div style={headerStyle}>第{index+1}优先级</div>*/}
                    <div style={headerStyle2}>
                    <FormItem
                        style={{width:'100%'}}
                    >
                        {getFieldDecorator('first'+(index+1)+'Rank', {
                            initialValue: {
                                selectValue:this.state.rowArr[index].contentType,
                                inputValue1: this.state.rowArr[index].beginLoc,
                                inputValue2: this.state.rowArr[index].endLoc,
                                inputValue3: this.state.rowArr[index].contentType,
                                inputValue4: this.state.rowArr[index].includeContent,
                                inputValue5: this.state.rowArr[index].includeContent,
                                ruleDetalId: this.state.rowArr[index].ruleDetalId,
                            },
                            rules: [
                                // {required: true, message:'请填写完整相应的表单'},
                                {type:'object', validator: this.checkObj,}
                            ],
                        })(
                            <CascadeSelectUrl index={index}  />
                        )}
                        </FormItem>
                    </div>

                    
                </div>

            )
        })
        return (
            <Form
                onSubmit={this.handleSubmit}
                style={{
                backgroundColor: '#fff',
                paddingTop: '20px',
                paddingBottom: '20px'
            }}>
            <div style={{width:'850px',height:'auto',margin:'0 auto'}}>
                <div style={headerStyle}>起始位置</div>
                <div style={headerStyle}>结束位置</div>
                <div style={headerStyle}>填充内容</div>
                <div style={headerStyle}>必含字段</div>
                <div style={headerStyle}>不包含值</div>
                <div style={headerStyle}>类型</div>
                {rowArr}
                <div style={{width:'350px', height:'auto', clear:'both', padding:'20px 0', margin:'0px auto'}}>
                    <Button type="primary" htmlType="submit" size="large" >
                        {this.state.loading?'提交中...':'确定'}
                    </Button>
                    <Button
                        type="default"
                        style={{marginLeft: '50px'}}
                        size="large"
                        onClick={()=>this.props.onCancel()}
                    >
                        取消
                    </Button>
                    <Button
                        type="default"
                        style={{marginLeft: '50px'}}
                        size="large"
                        onClick={this.addRow}
                    >
                        增加
                    </Button>
                </div>
            </div>
            </Form>
        );
    }
}
let MyForm = Form.create()(SelfForm);

export default class EditPage extends Component {
    constructor(props) {
		super(props);
		this.state = {
            loading: false,
            visible: false,
        };
        
    }
    handleOk = () => {
        // let result = this.state.resData;
        this.setState({
            visible: false,
        });
        this.refreshHandle();
    }

    handleCancel = () => {
        this.setState({
            visible: false,
        });
    }

    refreshHandle = () => {
        console.log("刷新List列表")
        this.props.refreshHandle();
    }
    // (外部调用)
    editHandle  = (resData,ruleCode) => {
        this.setState({
            visible: true,
            resData: resData,
            ruleCode:ruleCode,
        });




    }
    render() {
        return (
            <Modal
                    style={{top: '20px'}}
                    visible={this.state.visible}
                    title={'表单'}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    width={'850px'}
                    footer=''
                    maskClosable={false}
                    key={Math.random()}
                >
                    <MyForm
                        getData = {this.state.resData}
                        ruleCode = {this.state.ruleCode}
                        onCancel={this.handleCancel}
                        refreshHandle = {this.refreshHandle}
                     />
            </Modal>
        );
    }
}



class CascadeSelectUrl extends Component {
    constructor(props) {
        super(props);
        const value = this.props.value || {inputValue1: '',inputValue2: '',inputValue3: '',inputValue4: '',inputValue5: ''};
        this.state = {
            optionList:[],
            selectValue: value || {},
             //selectUrl需要传入的参数
            urlForSelect: '/getSelectData',
            urlForCascadeSelect: '',
            dicCode: 'dicCode',
            dicName: 'dicName',
        };
    }
    handleCurrencyChange = (value) => {
        if (!('value' in this.props)) {
                this.setState({selectValue:selectValue});
            }
        this.triggerChange(value);
    }
    triggerChange = (changedValue) => {
        // Should provide an event to pass value to Form.
        const onChange = this.props.onChange;
        if (onChange) {
            // onChange(JSON.stringify(changedValue));
            onChange(Object.assign(changedValue));
        }
    }

    getSelectValue = (value) => {
        let selectValue = this.state.selectValue;
        selectValue.selectValue = value;
        if (!('value' in this.props)) {
             this.setState({
                selectValue: selectValue
            })
        }
        this.triggerChange(selectValue);
    }
    inputChange1 = (e) => {
        // console.log('inputValue',e.target.value)
        let selectValue = this.state.selectValue;
        selectValue.inputValue1 = e.target.value;
        if (!('value' in this.props)) {
             this.setState({
                selectValue: selectValue
            })
        }
        this.triggerChange(selectValue);
    }

    inputChange2 = (e) => {
        // console.log('inputValue',e.target.value)
        let selectValue = this.state.selectValue;
        selectValue.inputValue2 = e.target.value;
        if (!('value' in this.props)) {
            this.setState({
                selectValue: selectValue
            })
        }
        this.triggerChange(selectValue);
    }

    inputChange3 = (e) => {
        // console.log('inputValue',e.target.value)
        let selectValue = this.state.selectValue;
        selectValue.inputValue3 = e.target.value;
        if (!('value' in this.props)) {
            this.setState({
                selectValue: selectValue
            })
        }
        this.triggerChange(selectValue);
    }

    inputChange4 = (e) => {
        // console.log('inputValue',e.target.value)
        let selectValue = this.state.selectValue;
        selectValue.inputValue4 = e.target.value;
        if (!('value' in this.props)) {
            this.setState({
                selectValue: selectValue
            })
        }
        this.triggerChange(selectValue);
    }

    inputChange5 = (e) => {
        // console.log('inputValue',e.target.value)
        let selectValue = this.state.selectValue;
        selectValue.inputValue5 = e.target.value;
        if (!('value' in this.props)) {
            this.setState({
                selectValue: selectValue
            })
        }
        this.triggerChange(selectValue);
    }

    componentDidMount() {
        if(this.state.selectValue.selectValue){
            let selectValue = this.state.selectValue.selectValue;
            this.setState({
                urlForCascadeSelect: '/wmsrest/product/prolocassingment/r/'+selectValue+'/mdlocation'
            })
        }

    }
    render() {
        const headerStyle = {
            float: 'left',
            width: '120px',
            textAlign: 'center',
            fontSize: '14px',
            margin: '0 5px'
        }
        const value = this.state.selectValue;
        return (
            <div style={{width:'850px',height:'auto',margin:'0 auto'}}>
                <div style={headerStyle}>
                    <Input value={value.inputValue1} onChange={this.inputChange1} />
                </div>
                <div style={headerStyle}>
                    <Input value={value.inputValue2} onChange={this.inputChange2} />
                </div>
                <div style={headerStyle}>
                    <Input value={value.inputValue3} onChange={this.inputChange3} />
                </div>

                <div style={headerStyle}>
                    <Input value={value.inputValue4} onChange={this.inputChange4} />
                </div>

                <div style={headerStyle}>
                    <Input value={value.inputValue5} onChange={this.inputChange5} />
                </div>

                <div style={headerStyle}>
                    <Select
                        placeholder="请选择"
                        showSearch
                        allowClear
                        onChange={this.getSelectValue}
                    >
                    <Option key={0} value={'0'}>日期</Option>
                    <Option key={1} value={'1'}>流水号</Option>

                    </Select>
                </div>
            </div>
        );
    }
}
